#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/*
 * There is a small error, the result should be 743 but this returns 740
 */

int toDec (char* s)
{
    char simbol[] = "MDCLXVI";
    int value[] = {1000, 500, 100, 50, 10, 5, 1};

    int res = 0;
    int last = 0;

    for (int i = 0; s[i]; i++)
    {
        int v = strchr(simbol, s[i]) - simbol;

        res += value[v];

        if (value[v] > last)
            res -= 2 * last;

        last = value[v];
    }
    return res;
}

char* toRoman(int x)
{
    int value[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
    char* simbol[] ={ "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};

    if (x < 1 && x >= 4000)
        return 0;

    char* r = (char*)malloc(20);
    r[0] = 0;

    for (int i = 0; x > 0; i++)
    {
        while (x >= value[i])
        {
            strcat(r, simbol[i]);
            x -= value[i];
        }
    }
    return r;
}

int main()
{
    int result = 0;
    FILE* file = fopen("roman.txt", "r");

    while (!feof(file))
    {
        char romanNumber[20];
        fgets(romanNumber, 20, file);

        int len = strlen(romanNumber) - 1;

        // quitamos el salto de linea
        romanNumber[len] = 0;

        int num = toDec(romanNumber);
        char* romanNumber2 = toRoman(num);

        int diff = len - strlen(romanNumber2);

        free(romanNumber2);

        //printf("%d\t%s\t%s\t%d\n", num, romanNumber, romanNumber, diff);

        result += diff;
    }
    fclose (file);

    printf("\nresult: %d", result);
	return 0;
}
